import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  FlatList,
  ActivityIndicator,
  TouchableOpacity,
  TouchableWithoutFeedback,
  RefreshControl,
  Keyboard,
  PermissionsAndroid,
  Platform,
  Button,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  ImageButton,
  LinearBoardButton,
  LinearButton,
  TextButton,
} from '../../components/Button';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {getFollowList, query} from '../../api/user';
import {showToast} from '../../components/Toast';
import {updateUserInfo} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import {BASE_API} from '../../config';
import LinearGradient from 'react-native-linear-gradient';
import {ScrollView} from 'react-native-gesture-handler';
import ModalHandler from '../../components/ModalHandler';

class UserFollowersScreen extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      followers: [],
      isRefreshing: false,
      page: 1,
      size: 10,
      total: 0,
      isLoadMore: false,
    };
  }

  componentDidMount() {
    this.onRefresh();
  }

  _onPressItem = (item) => {
    this._showLoading();

    console.log('_onPressItem', item);

    query({userToken: this.props.userInfo.token, identify: item.identify})
      .then((res) => {
        this._hideLoading();
        this.props.navigation.push('UserInfo', {
          user: res.data,
        });
      })
      .catch((err) => {
        this._hideLoading();
        console.log('查询出错' + JSON.stringify(err));
      });
  };

  _renderItem = (item) => {
    let follower = item.item;
    console.log('_renderItem follower', follower);
    let avatar =
      follower.image.indexOf('http') == -1
        ? BASE_API + follower.image
        : follower.image;
    return (
      <TouchableOpacity onPress={() => this._onPressItem(follower)}>
        <View
          style={{
            paddingHorizontal: 20,
            paddingVertical: 8,
            flexDirection: 'row',
            alignItems: 'center',
          }}>
          <Image
            style={{
              width: 60,
              height: 60,
              borderRadius: 33,
            }}
            source={{uri: avatar}}
          />
          <View
            style={{
              flexDirection: 'column',
              paddingHorizontal: 10,
              flex: 1,
            }}>
            <Text style={{color: '#fff', fontSize: 20, fontWeight: 'bold'}}>
              {follower.nickName}
              <Text style={{color: '#fff', fontSize: 20}}>
                @{follower.identify}
              </Text>
            </Text>
            <Text
              style={{color: '#fff', fontSize: 16, marginTop: 4}}
              numberOfLines={1}
              ellipsizeMode="tail">
              {follower.introduction}
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        No follower yet
      </Text>
    </View>
  );

  _renderItemSeparatorComponent = () => (
    <View style={{height: 0, backgroundColor: 'transparent'}} />
  );

  footerComponent = () => {
    let showLoadingMore = this.state.total >= this.state.page * this.state.size;
    return this.state.followers.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : 'no more data'}
          </Text>
        </View>
      </View>
    );
  };

  listEndReached() {
    const {page, isLoadMore, total, followers} = this.state;

    if (followers.length < total && !isLoadMore) {
      this.setState(
        {
          page: page + 1,
          isLoadMore: true,
        },
        () => {
          this.fetchData();
        },
      );
    }
  }

  onRefresh = async () => {
    this.setState({
      isRefreshing: true,
    });

    await this.fetchData();

    this.setState({
      isRefreshing: false,
    });
  };

  fetchData = async () => {
    let {page, size} = this.state;
    console.log('userToken', this.props.userInfo.token);
    getFollowList({
      userToken: this.props.userInfo.token,
      type: 0,
      page,
      size,
    })
      .then((res) => {
        console.log('getFollowingList', JSON.stringify(res));
        var followers = res.data.rows.map((item) => {
          return {
            ...item,
          };
        });
        if (page !== 1) {
          followers = this.state.followers.concat(followers);
        }
        this.setState({
          followers: followers,
          total: res.data.pageInfo.total,
        });
      })
      .catch((err) => {
        console.log(err);
        showToast(err.msg || 'falied');
      });
  };

  renderComponent = () => {
    let {followers, isRefreshing} = this.state;

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Followers"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              console.log(111);
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <FlatList
          showsVerticalScrollIndicator={false}
          style={{marginTop: 0}}
          data={followers}
          keyExtractor={(item, index) => index} // 给定的item生成一个不重复的key
          renderItem={this._renderItem}
          ListEmptyComponent={this._renderEmptyView}
          ItemSeparatorComponent={this._renderItemSeparatorComponent}
          ListFooterComponent={this.footerComponent}
          onEndReached={() => this.listEndReached()}
          onEndReachedThreshold={0.2}
          contentContainerStyle={{flexGrow: 1}}
          ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
          refreshControl={
            <RefreshControl
              tintColor="white"
              refreshing={isRefreshing}
              onRefresh={this.onRefresh}
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
        />
        <View
          style={{
            width: '100%',
            height: this.props.widgetLayout.show
              ? this.props.widgetLayout.height
              : 0,
            marginTop: 10,
          }}></View>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(UserFollowersScreen);
